#include "socket.hpp"
#include <iostream>
#include <memory>
#include <pthread.h>
#include <sys/wait.h>
using namespace socketmodule;
using namespace logmodule;

class TcpServer
{
    public:
    TcpServer(uint16_t port)
    :_port(port)
    ,_listensocket(std::make_unique<Tcpsocket>())
    ,_isrunning(false)
    {
        _listensocket->BuildTcpsocket(_port);
    }
    void start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            inetaddr client;
            auto sock = _listensocket->accepting(&client);//等待连接
            //得到文件描述符
            //得到客户端ip地址
            if(sock==nullptr)
            {
                continue;//一直等待
            }
            LOG(loglevel::INFO)<<"accept success!";
            pid_t tid = fork();
            if(tid<0)
            {
                LOG(loglevel::FATAL)<<"fork error...";
                exit(4);
            }
            else if(tid==0)
            {
                //子进程
                _listensocket->close();
                if(fork()<0)
                {
                    exit(1);
                }
            }
            else{
                sock->close();
                pid_t ttid = ::waitpid(tid,nullptr,0);//等待
                (void)ttid;
            }
        }

        
        _isrunning = false;
    }
    ~TcpServer()
    {}
    private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensocket;
    bool _isrunning;
};